// 引入创建分类仓库的APi方法
import { defineStore } from "pinia";
// 引入分类列表数据的类型
import type { CategoryListModel, CategoryIdsModel, Numberable } from "@/api/product/model/categoryModel";

//引入API接口函数
import { reqGetcategory1List, reqGetcategory2List, reqGetcategory3List } from "./../api/product/category";

// 自定义一个可以存放三个分类列表的接口类型
export interface CategoryStateModel extends CategoryIdsModel {
  category1List: CategoryListModel;
  category2List: CategoryListModel;
  category3List: CategoryListModel;
}

export const useCategoryStore = defineStore({
  id: "category",
  // 状态数据
  state: (): CategoryStateModel => {
    return {
      category1Id: undefined, //一级分类的id
      category2Id: undefined, //二级分类的id
      category3Id: undefined, //三级分类的id
      category1List: [], //一级分类的列表数据
      category2List: [], //二级分类的列表数据
      category3List: [], //三级分类的列表数据
    };
  },

  //计算属性
  getters: {
    //一级分类的id的获取
    getCategory1Id(): Numberable {
      return this.category1Id;
    },
    //二级分类的id的获取
    getCategory2Id(): Numberable {
      return this.category2Id;
    },
    //三级分类的id的获取
    getCategory3Id(): Numberable {
      return this.category3Id;
    },
    //获取一级分类列表的数据
    getCategoryList1(): CategoryListModel {
      return this.category1List;
    },
    //获取二级分类列表的数据
    getCategoryList2(): CategoryListModel {
      return this.category2List;
    },
    //获取三级分裂列表的数据
    getCategoryList3(): CategoryListModel {
      return this.category3List;
    },
  },

  //定义获取列表数据的函数actions

  actions: {
    //获取一分类列表数据
    async getCategory1List() {
      this.category1List = await reqGetcategory1List();
    },

    //获取二级分类列表数据
    async getCategory2List(category1Id: number) {
      // 先存储一份一级分类的id数据
      this.category1Id = category1Id;
      //随后得到二级分类的列表数据
      this.category2List = await reqGetcategory2List(category1Id);
      //清除二级与三级的数据，要不切换的时候会有bug
      this.category2Id = undefined;
      this.category3Id = undefined;
      this.category3List = [];
    },

    //获取三级分类列表数据
    async getCategory3List(category2Id: number) {
      //先存储一份2id的数据
      this.category2Id = category2Id;
      //得到三级列表的数据
      this.category3List = await reqGetcategory3List(category2Id);
      //只需要清除三级id即可
      this.category3Id = undefined;
    },
  },
});

// 暴露这个仓库
export default useCategoryStore;
